package com.tqw.order.service.imp;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.tqw.entity.Result;
import com.tqw.exception.TqwExcepition;
import com.tqw.item.feign.ItemFeignClient;
import com.tqw.order.constants.OrderConstant;
import com.tqw.order.mapper.OrderMapper;
import com.tqw.pojo.Order;
import com.tqw.order.service.OrderService;
import com.tqw.order.vo.*;
import com.tqw.pojo.Item;
import com.tqw.shipping.feign.ShippingFeignClient;
import com.tqw.util.IdWorker;
import com.tqw.vo.ShippingVO;
import ma.glasnost.orika.MapperFacade;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestHeader;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @Author: czm
 * @Date: 2022/04/07/23:38
 * @Description:
 */
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private ShippingFeignClient shippingFeign;

    @Autowired
    private ItemFeignClient itemFeignClient;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private MapperFacade mapperFacade;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public OrderConfirmVO getOrderItemInfo(Integer clientId, Integer itemId) {
        Result<Item> item = itemFeignClient.findItemById(itemId);
        OrderItemVO orderItemVO = mapperFacade.map(item.getData(), OrderItemVO.class);
        OrderConfirmVO orderConfirmVO = new OrderConfirmVO();
        orderConfirmVO.setOrderItemVO(orderItemVO);
        return orderConfirmVO;
    }

    @Override
    public Result submit(Integer clientId, OrderSubmitVO orderSubmitVO) {
        //调用商品远程接口,修改商品的状态
        //首先修改缓存的商品状态
        Result<Item> itemResult = itemFeignClient.findItemById(orderSubmitVO.getItemId());
        if (itemResult.getData().getStatus()=='2'){
            Result<Object> result = new Result<>();
            result.setFlag(false);
            result.setCode(OrderConstant.ORDERFAIL);
            result.setMessage("商品已售出,请重新下单");
            return result;
        }

        itemFeignClient.updateItemDesc(orderSubmitVO.getItemId(),'2');

        Item item = new Item();
        //再修改数据库商品的状态
        item.setStatus('2').setId(orderSubmitVO.getItemId());
        Result<?> result = itemFeignClient.updateItemStatus(item);
        if (result.getCode()==200){
            //发送延时消息,超时30分钟若还未支付则取消订单
            String orderId = String.valueOf(new IdWorker().nextId());
            SendStatus sendStatus = rocketMQTemplate.syncSend(OrderConstant.ORDER_CANCEL_TOPIC, new GenericMessage<>(orderId),
                    OrderConstant.TIMEOUT, OrderConstant.CANCEL_ORDER_DELAY_LEVEL).getSendStatus();
            if (!Objects.equals(sendStatus,SendStatus.SEND_OK)) {
                // 消息发不出去就抛异常，发的出去无所谓
                throw new TqwExcepition();
            }
            orderSubmitVO.setOrderId(orderId).setClientId(clientId).setStatus(OrderConstant.ORDER_NO_PAY);
            Order order = mapperFacade.map(orderSubmitVO, Order.class);
            orderMapper.insert(order);
        }else {
            throw new TqwExcepition("订单保存失败");
        }
        Result<Object> objectResult = new Result<>();
        objectResult.setData(orderSubmitVO.getOrderId());
        return objectResult;
    }

    @Override
    public PageOrderResult getOrderList(PageOrderResult pageResult) {
        if (pageResult.getQuery()==4){
            /*获取当前用户的订单总数*/
            Long orderTotal = orderMapper.getOrderTotal(pageResult.getClientId());
            int start = (pageResult.getPageNum() - 1) * pageResult.getPageSize();
            int size = pageResult.getPageSize();
            Integer clientId = pageResult.getClientId();
            List<OrderListItemVO> rows = orderMapper.getOrderList(start, size, clientId);
            return pageResult.setTotal(orderTotal).setRows(rows);
        }else {
            /*获取不同订单状态的订单总数*/
            Long otherOrderTotal = orderMapper.getOtherOrderTotal(pageResult.getClientId(), pageResult.getQuery());
            int start = (pageResult.getPageNum() - 1) * pageResult.getPageSize();
            int size = pageResult.getPageSize();
            Integer clientId = pageResult.getClientId();
            List<OrderListItemVO> rows = orderMapper.getOtherOrderList(start, size, clientId,pageResult.getQuery());
            return pageResult.setTotal(otherOrderTotal).setRows(rows);
        }
    }

    @Override
    public OrderDescVO getOrderDesc(String orderId,Integer clientId) {
        Order orderInfo = orderMapper.getOrderInfoByOrderId(orderId);
        //远程调用商品服务接口查询商品信息
        Result<Item> itemInfo = itemFeignClient.findItemById(orderInfo.getItemId());
        //远程调用地址服务接口出现收货地址
        Result<ShippingVO> shippingVOResult = shippingFeign.getInfoById(orderInfo.getReceivingId(), clientId);
        System.out.println(shippingVOResult);
        OrderDescVO orderDescVO = new OrderDescVO();
        orderDescVO.setItemId(orderInfo.getItemId())
                .setOrderId(orderInfo.getOrderId())
                .setAddressDetail(shippingVOResult.getData().getAddressDetail())
                .setConsignee(shippingVOResult.getData().getConsignee())
                .setCityName(shippingVOResult.getData().getCityName())
                .setCreatedTime(orderInfo.getCreatedTime())
                .setPaidTime(orderInfo.getPaidTime())
                .setPhone(shippingVOResult.getData().getPhone())
                .setProvinceName(shippingVOResult.getData().getProvinceName())
                .setRegionName(shippingVOResult.getData().getRegionName())
                .setStreetName(shippingVOResult.getData().getStreetName())
                .setPrice(orderInfo.getPrice())
                .setStatus(orderInfo.getStatus())
                .setPayType(orderInfo.getPayType())
                .setFontImage(itemInfo.getData().getFontImage())
                .setTitle(itemInfo.getData().getTitle())
                .setSellPoint(itemInfo.getData().getSellPoint());
        return orderDescVO;
    }

    @Override
    public void delete(String orderId) {
        orderMapper.delete(orderId);
    }

    @Override
    public void cancel(String orderId) {
        Order orderInfo = orderMapper.getOrderInfoByOrderId(orderId);
        Integer itemId = orderInfo.getItemId();
        Item item = new Item();
        item.setStatus('1').setId(itemId);
        itemFeignClient.updateItemStatus(item);
        orderMapper.cancel(orderId);
    }

    @Override
    public OrderPayInfoVO getOrderPayInfo(String orderId) {
        Order orderInfo = orderMapper.getOrderInfoByOrderId(orderId);
        OrderPayInfoVO orderPayInfoVO = mapperFacade.map(orderInfo, OrderPayInfoVO.class);
        return orderPayInfoVO;
    }

    @Override
    public void orderPay(OrderPayInfoVO orderPayInfoVO) {
        orderPayInfoVO.setPaidTime(new Date());
        Order order = mapperFacade.map(orderPayInfoVO, Order.class);
        order.setStatus(OrderConstant.ORDER_PAID);
        UpdateWrapper<Order> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("order_id", order.getOrderId());
        orderMapper.update(order, updateWrapper);
    }

    @Override
    public void updateOrder(String orderId) {
        Order order = new Order();
        order.setOrderId(orderId).setStatus(OrderConstant.ORDER_PAID)
                .setPaidTime(new Date()).setPayType(OrderConstant.ALIPAY_ORDER_PAY);
        UpdateWrapper<Order> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("order_id",orderId);
        orderMapper.update(order,updateWrapper);
    }



    @Override
    public OrderPaySuccessVO getOrderPaySuccessInfo(String orderId) {
        Order orderInfo = orderMapper.getOrderInfoByOrderId(orderId);
        Integer streetId = orderInfo.getReceivingId();
        Result<ShippingVO> shippingFeignInfo = shippingFeign.getInfoById(streetId, orderInfo.getClientId());
        OrderPaySuccessVO orderPaySuccessVO = new OrderPaySuccessVO();
        orderPaySuccessVO.setOrderId(orderId)
                .setPrice(orderInfo.getPrice())
                .setProvinceName(shippingFeignInfo.getData().getProvinceName())
                .setCityName(shippingFeignInfo.getData().getCityName())
                .setRegionName(shippingFeignInfo.getData().getRegionName())
                .setStreetName(shippingFeignInfo.getData().getStreetName())
                .setAddressDetail(shippingFeignInfo.getData().getAddressDetail());
        return orderPaySuccessVO;
    }

    @Override
    public void updatePayOrder(String orderId) {
        Order orderInfo = orderMapper.getOrderInfoByOrderId(orderId);
        Integer clientId = orderInfo.getClientId();
        Order order = new Order();
        order.setOrderId(orderId).setStatus(OrderConstant.ORDER_PAID)
                .setPaidTime(new Date()).setPayType(OrderConstant.ALIPAY_ORDER_PAY).setUpdateBy(clientId);
        System.out.println(order);
        orderMapper.updatePayOrder(order);
    }
}
